package org.zhangxiao.paladin2.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * Cookie工具类
 */
public class CookieUtils {


    private static final Log LOG = LogFactory.getLog(CookieUtils.class);

    private static final Integer COOKIE_MAX_AGE = 3600;

    private static final Boolean COOKIE_SECURE = true;

    private static final Boolean COOKIE_HTTP_ONLY = true;

    public static void saveCookie(HttpServletResponse response, String fieldName, String fieldValue) {
        saveCookie(response,fieldName,fieldValue, COOKIE_MAX_AGE);
    }

    public static void saveCookie(HttpServletResponse response, String fieldName, String fieldValue, int maxAge) {
        if (StringUtils.hasText(fieldName)) {
            Cookie cookie = new Cookie(fieldName, fieldValue);
            cookie.setSecure(COOKIE_SECURE);
            cookie.setHttpOnly(COOKIE_HTTP_ONLY);
            cookie.setPath("/");
            cookie.setMaxAge(maxAge);
            response.addCookie(cookie);
        }
    }

    public static void removeCookie(HttpServletResponse response, String fieldName) {
        if (StringUtils.hasText(fieldName)) {
            Cookie cookie = new Cookie(fieldName, "");
            cookie.setSecure(COOKIE_SECURE);
            cookie.setHttpOnly(COOKIE_HTTP_ONLY);
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
    }

    public static Optional<Cookie> getCookie(HttpServletRequest request, String fieldName) {
        return Optional.ofNullable(WebUtils.getCookie(request, fieldName));
    }

    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        Optional<Cookie> cookie = getCookie(request, cookieName);
        if (cookie.isPresent()) {
            return cookie.get().getValue();
        }
        return "";
    }

    public static void cleanUp(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            removeCookie(response, cookie.getName());
        }
    }
}
